package com.sxkiler.demo.web.config;//package com.sxkiler.demo.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidMySqlAutoConfig {

    private static Logger logger = LoggerFactory.getLogger(DruidMySqlAutoConfig.class);

    @Bean
    @ConfigurationProperties("spring.datasource.druid.write")
    public DataSource dataSourceMaster(){
        logger.info("初始化主库数据源");
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.read")
    public DataSource dataSourceSlave(){
        logger.info("初始化从库数据源");
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    @DependsOn({ "dataSourceMaster", "dataSourceSlave" })
    @ConditionalOnMissingBean(name = "dynamicDataSource")
    public DynamicDataSource dynamicDataSource(
            @Qualifier("dataSourceMaster") DataSource dataSourceMaster,
            @Qualifier("dataSourceSlave") DataSource dataSourceSlave){
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>(8);
        targetDataSources.put(DynamicDataSourceHolder.DATA_SOURCE_WRITE,dataSourceMaster);
        targetDataSources.put(DynamicDataSourceHolder.DATA_SOURCE_READ,dataSourceSlave);
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.setDefaultTargetDataSource(dataSourceMaster);
        logger.info("初始化动态数据源");
        return dynamicDataSource;
    }


}